#!/usr/bin/env python3

# Copyright (C) 2020  Matthew "strager" Glazar
# See end of file for extended copyright information.

from qljs_external_test_suite import match_path, run_quick_lint_js
import argparse
import json
import os
import pathlib
import pipes
import subprocess
import sys
import typing
import unittest


TODO_JS_FILES = (
    "JSX/*",
    "multiline_string_literal.js",
)


def main() -> None:
    arg_parser = argparse.ArgumentParser()
    arg_parser.add_argument("quick_lint_js_exe")
    arg_parser.add_argument("esprima_tests")
    args = arg_parser.parse_args()

    quick_lint_js_executable = pathlib.Path(args.quick_lint_js_exe)
    esprima_test_fixture_directory = pathlib.Path(args.esprima_tests)

    test_files = sorted(esprima_test_fixture_directory.glob("**/*.js"))
    for test_file in test_files:
        test_file = test_file.resolve()
        if not should_check_js_file(test_file):
            continue
        lint_result = run_quick_lint_js(
            quick_lint_js_executable=quick_lint_js_executable, js_file=test_file
        )
        if lint_result.crashed:
            lint_result.dump()
            exit(1)


def should_check_js_file(js_file: pathlib.Path) -> bool:
    return not is_todo(js_file) and not test_failure_is_expected(js_file)


def is_todo(path: pathlib.Path) -> bool:
    return any(
        match_path(pattern=todo_pattern, path=path) for todo_pattern in TODO_JS_FILES
    )


def test_failure_is_expected(path: pathlib.Path) -> bool:
    if path.with_suffix(".failure.json").exists():
        return True
    try:
        with open(path.with_suffix(".tree.json")) as tree_file:
            esprima_tree = json.load(tree_file)
        if esprima_tree.get("errors", ()):
            return True
    except FileNotFoundError:
        pass
    return False


if __name__ == "__main__":
    main()

# quick-lint-js finds bugs in JavaScript programs.
# Copyright (C) 2020  Matthew "strager" Glazar
#
# This file is part of quick-lint-js.
#
# quick-lint-js is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# quick-lint-js is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with quick-lint-js.  If not, see <https://www.gnu.org/licenses/>.
